package com.hspedu.homework.Homework03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DL5O
 * @version 1.0
 */
public class Homework03Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999);//在9999端口监听
        System.out.println("服务端在9999端口监听，等待客服端连接...");
        Socket socket = serverSocket.accept();
        String filePath = "src\\高山流水.mp3";

        //1.接收从客服端发来的文件名信息
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String fileName = br.readLine();
        System.out.println("文件发来的文件名:"+fileName);

        //2.进行文件的判断，如果服务器有对应的文件，那么就进行读取后写入到数据通道中
        OutputStream os = socket.getOutputStream();
        if(fileName.equals("高山流水")){
            FileInputStream fi= new FileInputStream(filePath);
            byte[] bytes = StreamUtils.streamToByteArray(fi);
            System.out.println("读取文件成功...");
            fi.close();
            //3.写入到数据通道中
            os.write(bytes,0,bytes.length);
            os.flush();
            System.out.println("已传输二进制数据给客服端...");
        }else{
            os.flush();
            System.out.println("没有改文件");
        }
        socket.shutdownOutput();
        System.out.println("服务端退出...");
        os.close();
        br.close();
        socket.close();
    }
}
